//
//  UIImage+Crop.m
//  MeiDa
//
//  Created by zfc on 2019/10/25.
//  Copyright © 2019年 depelec. All rights reserved.
//

#import "UIImage+Crop.h"

@implementation UIImage (Crop)


//将图片裁剪成指定比例（多余部分自动删除）
- (UIImage *)crop:(CGFloat)ratio {
    CGSize newSize = CGSizeZero;
    if (self.size.width/self.size.height > ratio) {
        newSize = CGSizeMake(self.size.height * ratio, self.size.height);
    } else {
        newSize = CGSizeMake( self.size.width, self.size.width / ratio);
    }

    CGRect rect = CGRectZero;
    rect.size.width = self.size.width;
    rect.size.height = self.size.height;
    rect.origin.x = (newSize.width - self.size.width) /2.0;
    rect.origin.y = (newSize.height - self.size.height) /2.0;

//    CGContextRef *ref = UIGraphicsBeginImageContext(newSize);
//    CGContextDrawImage(ref, rect, self);

    UIGraphicsBeginImageContext(newSize);
    [self drawInRect:rect];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;

}


- (UIImage *)scaleToWidth:(CGFloat)width{

    // 如果传入的宽度比当前宽度还要大,就直接返回

    if (width > self.size.width) {
        return  self;
    }

    // 计算缩放之后的高度
    CGFloat height = (width / self.size.width) * self.size.height;

    // 初始化要画的大小
    CGRect  rect = CGRectMake(0, 0, width, height);

    // 1. 开启图形上下文
    UIGraphicsBeginImageContext(rect.size);

    // 2. 画到上下文中 (会把当前image里面的所有内容都画到上下文)
    [self drawInRect:rect];

    // 3. 取到图片

    UIImage * image = UIGraphicsGetImageFromCurrentImageContext();

    // 4. 关闭上下文
    UIGraphicsEndImageContext();
    // 5. 返回
    return image;
}


@end
